package com.aoxon.cargo.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.CallLog.Calls;
import android.provider.Telephony;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.aoxon.cargo.R;
import com.aoxon.cargo.adapter.PurGoodsPagerAdapter;
import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.RecordDial;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.component.MyLoadCloth;
import com.aoxon.cargo.database.DataService;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.CancleCollectGoodsService;
import com.aoxon.cargo.service.CollectGoodsService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.RecordDialService;
import com.aoxon.cargo.service.SupplierInformationService;
import com.aoxon.cargo.shared.CollectGoodsShared;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ExecutorUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * 商品详情页
 * 
 * @author Jiayu
 * 
 */
public class PurGoodsPagerActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	public static int START_ITEM = 0;

	private int colNum = -1; // 保存当前收藏所在收藏列表的位数
	private List<Cloth> colCloths; // 本地收藏列表
	private List<Cloth> disCloths; // 要显示用的列表

	private ViewPager mViewPager;
	private boolean cancleLoad = false;
	private ImageView ivBackButton;
	private ImageView ivPhoneButton;

	private RadioButton rbCollectButton;

	private PurGoodsPagerAdapter adapter;

	private DataService dataService = new DataService(this);
	private MyLoadCloth mLoadCloth = new MyLoadCloth();
	private CollectGoodsService collectGoodsService = (CollectGoodsService) MyServiceFactory
			.getInstance(MyServiceFactory.COLLECT_GOODS);
	private CancleCollectGoodsService cancleCollectGoodsService = (CancleCollectGoodsService) MyServiceFactory
			.getInstance(MyServiceFactory.CANCLE_COLLECT_GOODS);
	private SupplierInformationService supplierInformationService = (SupplierInformationService) MyServiceFactory
			.getInstance(MyServiceFactory.SUPPLIER_INFORMATION);
	private RecordDialService recordDialService = (RecordDialService) MyServiceFactory
			.getInstance(MyServiceFactory.RECORDDIAL);

	private boolean isReachLast = false;
	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);
	private java.text.DateFormat format = new java.text.SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private Supplier user = SupIndexShared.getSupplier();

	private String deviceId = null;
	private int loadType = 0; // 加载的数据源
	private int length = 12;// 每次加载的个数
	private int startIndex = 0; // 显示的总个数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setup();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		adapter.clear();
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		// colCloths = CollectGoodsShared.getColGoodsList();

		colCloths = dataService.getClothes(deviceId, 0, 100,
				MyStateUtil.COLLECTION_CLOTH);
		if (colCloths == null) {
			colCloths = new ArrayList<Cloth>();
		}
		checkCollected(disCloths.get(mViewPager.getCurrentItem()));
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			return false;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	private void setup() {
		setContentView(R.layout.pur_goods_details_page);

		try {
			TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			deviceId = telMgr.getDeviceId();
		} catch (Exception e) {
			e.printStackTrace();
		}

		mViewPager = (ViewPager) findViewById(R.id.vpPurGoodsDetailsPager);
		ivBackButton = (ImageView) findViewById(R.id.ivPurDetailsBack);
		ivPhoneButton = (ImageView) findViewById(R.id.ivPurDetailsPhone);
		rbCollectButton = (RadioButton) findViewById(R.id.rbPurDetailsCollection);

		Intent intent = getIntent();

		startIndex = intent.getIntExtra("startIndex", 0);
		length = intent.getIntExtra("length", 0);
		loadType = intent.getIntExtra("loadType", 0);

		disCloths = new ArrayList<Cloth>();
		disCloths = Collections
				.synchronizedList((List<Cloth>) MyLoadCloth.clothList);

		// disCloths = Collections
		// .synchronizedList((List<Cloth>) MyLoadCloth.clothList);

		adapter = new PurGoodsPagerAdapter(this, mViewPager, disCloths);

		normalDataLoader.setOnloadDataListener(this);
		adapter.notifyDataSetChanged();
		mViewPager.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		mViewPager.setCurrentItem(START_ITEM);
		mViewPager.setOnPageChangeListener(onPageChangeListener);

		// colCloths = CollectGoodsShared.getColGoodsList();

		colCloths = dataService.getClothes(deviceId, 0, 100,
				MyStateUtil.COLLECTION_CLOTH);
		if (colCloths == null) {
			colCloths = new ArrayList<Cloth>();
		}

		checkCollected(disCloths.get(START_ITEM));

		ivBackButton.setOnClickListener(onClickListener);
		ivPhoneButton.setOnClickListener(onClickListener);
		rbCollectButton.setOnClickListener(onClickListener);
	}

	/**
	 * 检测物品是否被收藏
	 * 
	 * @param cloth
	 * @return
	 */
	private int checkCollected(Cloth cloth) {
		if (cloth != null) {
			rbCollectButton.setChecked(false);
			if (colCloths != null) {
				for (int i = 0; i < colCloths.size(); i++) {
					if (cloth.getClothId() == colCloths.get(i).getClothId()) {
						rbCollectButton.setChecked(true);
						colNum = i;
						return i;
					}
				}
			}
		}
		return -1;

	}

	OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.ivPurDetailsBack:
				PurGoodsPagerActivity.this.finish();
				break;
			case R.id.ivPurDetailsPhone:
				callSup();
				break;

			case R.id.rbPurDetailsCollection:
//				collect();
				Cloth cloth = disCloths.get(mViewPager.getCurrentItem());
				if (colNum != -1) {
					colCloths.remove(colNum);
					colNum = -1;
					cloth.setCollectedNum(cloth.getCollectedNum() - 1);
					dataService.deleteCollection(deviceId, cloth.getClothId(),
							MyStateUtil.COLLECTION_CLOTH);
					rbCollectButton.setChecked(false);
					notifyCollect(cloth.getClothId(), true);
				} else {
					colNum = colCloths.size();
					colCloths.add(cloth);
					cloth.setCollectedNum(cloth.getCollectedNum() + 1);
					String time3;

					time3 = format.format(new Date());
					dataService
							.insertCloth(cloth, MyStateUtil.COLLECTION_CLOTH);
					dataService.insertStat(deviceId, cloth.getClothId(),
							MyStateUtil.COLLECTION_CLOTH, time3);

					notifyCollect(cloth.getClothId(), false);
				}
				// CollectGoodsShared.saveColGoodsList(colCloths);
				if (MyLoadCloth.waterFallGoodsView != null) {
					MyLoadCloth.waterFallGoodsView.updateCollectNum(
							cloth.getClothId(), cloth.getCollectedNum());
				}
				break;
			default:
				break;
			}
		}
	};

	OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			colNum = -1;
			checkCollected(disCloths.get(position));
			Log.i("pageChange",
					"--------------------------------------------position:"
							+ position + ", size:" + disCloths.size());
			if (position + 1 == disCloths.size()) {
				if (mLoadCloth != null) {
					if (loadType != MyLoadCloth.COLLECT) {
						Log.i("load",
								"--------------------加载新数据------------------------");
						normalDataLoader.load();

					}
				}
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}
	};

	// 通知服务器收藏操作
	private void notifyCollect(final int clothId, final boolean cancleCollect) {
		ExecutorUtil.getCachedExecutorService().submit(new Runnable() {
			@Override
			public void run() {
				if (EnvironmentUtil.checkNetState(getBaseContext())) {
					try {
						if (cancleCollect) {
							cancleCollectGoodsService.execute(clothId);
						} else {
							collectGoodsService.execute(clothId);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					ToastUtil.show(PurGoodsPagerActivity.this, "无网络连接~");
				}
			}
		});
	}


	private void callSup() {
		ExecutorUtil.getCachedExecutorService().submit(new Runnable() {
			@Override
			public void run() {
				try {
					TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
					RecordDial rd = new RecordDial();
					rd.setImei(telMgr.getDeviceId());
					String operator = telMgr.getNetworkOperator();
					if (operator != null) {
						switch (Integer.parseInt(operator)) {
						case 46000:
							rd.setProviderName("移动");
						case 46001:
							rd.setProviderName("联通");
						case 46002:
							rd.setProviderName("电信");
						}
					}

					rd.setFromPhone(telMgr.getLine1Number());

					Log.v("tel", DataUtil.gson.toJson(rd));
					int supId = disCloths.get(mViewPager.getCurrentItem())
							.getSupId();
					Supplier supplier = dataService.getSupplier(supId);
					if (supplier == null) {
						GsonBean gsonBean = supplierInformationService
								.execute(supId);
						if (CheckStateUtil.check(gsonBean)) {
							supplier = DataUtil.gson.fromJson(
									gsonBean.getStrJson(), Supplier.class);
						}
					}

					int fromId = 0, toId = 0;
					String time;
					time = format.format(new Date());
					if (supplier != null) {
						rd.setToSupId(supplier.getSupId());
						rd.setToPhone(supplier.getSupPhone());
						GsonBean gsonBean = recordDialService.execute(rd);
						Log.v("dial gsonbean", DataUtil.gson.toJson(gsonBean));
						// 保存拨打记录
						// DialShared.saveDialRecord(supplier);
						toId = supplier.getSupId();
						if (user != null) {
							fromId = user.getSupId();
						}
						dataService.insertStat(deviceId, toId,
								MyStateUtil.PHONE_RECORD, time);
						dataService
								.insertSupplier(supplier, MyStateUtil.COMMOM);
						Intent intent = new Intent(Intent.ACTION_CALL, Uri
								.parse("tel:" + supplier.getSupPhone()));
						startActivity(intent);
					}

				} catch (JsonSyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					ToastUtil.show(getBaseContext(), "供应商电话信息出错!");
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		if (normalDataLoader.getLoading()) {
			ToastUtil.show(this, "加载中~");
		}
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		if (isReachLast) {
			msg.what = MyStateUtil.LIST_IS_REACH_LAST;
			return;
		}
		GsonBean gsonBean = mLoadCloth.loadCloths(startIndex, length, loadType);
		if (CheckStateUtil.check(gsonBean)) {
			List<Cloth> newCloths = DataUtil.gson.fromJson(
					gsonBean.getStrJson(), new TypeToken<List<Cloth>>() {
					}.getType());
			if (!cancleLoad) {
				disCloths.addAll(newCloths);
				startIndex += newCloths.size();
				msg.what = MyStateUtil.LIST_CHANGE;
				Log.e("GoodPager", "NoCancel");
			} else
				Log.e("GoodPager", "HasCancel");
		} else {
			// 查找不到数据的情况
			isReachLast = true;
			msg.what = MyStateUtil.LIST_IS_REACH_LAST;
		}
	}

	@SuppressLint("NewApi")
	private void callRecord(Context context) {
		try {
			ContentResolver cr = context.getContentResolver();
			Cursor cursor = cr.query(Telephony.Threads.CONTENT_URI,
					new String[] { Telephony.Threads._ID,
							Telephony.Threads.DATE,
							Telephony.Threads.RECIPIENT_IDS,
							Telephony.Threads.MESSAGE_COUNT,
							Telephony.Threads.READ, Telephony.Threads.SNIPPET,
							Telephony.Threads.SNIPPET_CHARSET,
							Telephony.Threads.TYPE, Telephony.Threads.ERROR,
							Telephony.Threads.HAS_ATTACHMENT }, null, null,
					Telephony.Threads.DATE + " desc");
			// CallLog.Calls.CONTENT_URI,
			// new String[] { CallLog.Calls.NUMBER, // 电话号码
			//
			// CallLog.Calls.CACHED_NAME, // 联系人
			//
			// CallLog.Calls.TYPE, // 通话类型
			//
			// CallLog.Calls.DATE, // 通话时间
			//
			// CallLog.Calls.DURATION // 通话时长
			//
			// }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);

			int i = 5;
			if (cursor.moveToFirst()) {
				do {
					// CallsLog calls =new CallsLog();
					// 号码
					String number = cursor.getString(cursor
							.getColumnIndex(Calls.NUMBER));
					// 呼叫类型
					String type;
					switch (Integer.parseInt(cursor.getString(cursor
							.getColumnIndex(Calls.TYPE)))) {
					case Calls.INCOMING_TYPE:
						type = "呼入";
						break;
					case Calls.OUTGOING_TYPE:
						type = "呼出";
						break;
					case Calls.MISSED_TYPE:
						type = "未接";
						break;
					default:
						type = "挂断";// 应该是挂断.根据我手机类型判断出的
						break;
					}
					SimpleDateFormat sfd = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					Date date = new Date(Long.parseLong(cursor.getString(cursor
							.getColumnIndexOrThrow(Calls.DATE))));
					// 呼叫时间
					String time = sfd.format(date);
					// 联系人
					String name = cursor.getString(cursor
							.getColumnIndexOrThrow(Calls.CACHED_NAME));
					// 通话时间,单位:s
					String duration = cursor.getString(cursor
							.getColumnIndexOrThrow(Calls.DURATION));
					i--;

				} while (cursor.moveToNext() && i > 0);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		switch (state) {
		case MyStateUtil.LIST_CHANGE:
			Log.i("listChange",
					"------------------listChange--------------------");
			break;
		case MyStateUtil.LIST_IS_REACH_LAST:
			ToastUtil.show(getBaseContext(), "没有更多数据咯~");
			break;
		default:
			break;
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		cancleLoad = true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		cancleLoad = false;
		if (START_ITEM == disCloths.size() - 1
				&& loadType != MyLoadCloth.COLLECT) {
			// 第一个显示出来的页面是数据的最后一个且不是加载本地收藏数据时，自动从网上获取接下去的数据
			normalDataLoader.load();
		}
	}
}
